package com.bodystm.controller;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.system.SystemSetting;
import com.bodystm.system.SystemSettingService;
import com.bodystm.user.CustomUserService;
import com.mimosa.common.dao.PropertyFilter;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.TUserDao;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.util.config.Page;
import com.mimosa.util.config.YesNoType;


@Controller
@RequestMapping("/user")
public class UserController {
	/**
	 * 日志记录器
	 */
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private CustomUserService customUserService;
	@Autowired
	private SystemSettingService systemSettingService;

	protected String getMappingPath() {
		return "";
	}

	protected String getEntityName() {
		return "user";
	}

	@RequestMapping(value = { "/index.action" })
	public String index(Page<TUser> page, HttpServletRequest request, Model model) {
		
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		PropertyFilter stateFilter = new PropertyFilter("EQS_state", YesNoType.Y.name());
		filters.add(stateFilter);

		if (StringUtils.isBlank(page.getOrderBy())) {
			page.setOrder(Page.DESC);
			page.setOrderBy("createTime");
		}
		Page<TUser> resultPage = this.customUserService.findByPage(page, filters);
		SystemSetting systemSetting=systemSettingService.getSystemSetting();
		if(systemSetting!=null){
			model.addAttribute("logoPath", systemSetting.getHospitalLogoPath());
		}
		logger.info("user count:"+resultPage.getResult().size());
		model.addAttribute("resultPage", resultPage);
		//return this.getMappingPath() + this.getEntityName() + "/index";
		return this.getMappingPath() + this.getEntityName() + "/BackstageManagement";
	}
	
	@ResponseBody
	@RequestMapping("/list.action")
	public String list(Page<TUser> page) {
		//page = this.patientService.findByPage(page);
		Page<TUser> users;
		users=customUserService.findByPage(page,Restrictions.eq("usable", 1));
		StringBuilder builder = new StringBuilder("{\"total\":\"");
		builder.append(users.getTotalCount());
		builder.append("\",\"rows\":[");
		for (TUser user : users.getResult()) {
			builder.append("{\"id\":\"").append(user.getId());
			builder.append("\",\"realName\":\"").append(user.getRealName());
			builder.append("\",\"userName\":\"").append(user.getUserName());
			builder.append("\",\"userPass\":\"").append(user.getUserPass()).append("\"},");
		}
		if(users.getResult().size()>0)
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]}");
		return builder.toString();
	}
	
	@ResponseBody
	@RequestMapping(value = { "/save" })
	public String save(@ModelAttribute("preloadEntity") TUser entity) {
		if (StringUtils.isBlank(entity.getId())) {
			if(this.customUserService.getUserByName(entity.getUserName())!=null){
				return "{\"success\":false}";
			}
			this.customUserService.saveEntity(entity);
		} else {
			this.customUserService.updateEntity(entity);
		}
		return "{\"success\":true}";
		//return EntityController.REDIRECT_URL;
	}

	@RequestMapping(value = { "/delete" })
	public String delete(String id) {
		this.customUserService.deleteEntity(id);
		return EntityController.REDIRECT_URL;
	}
	@ResponseBody
	@RequestMapping(value = { "/deleteUserById" })
	public String deleteUserById(String id) {
		//this.customUserService.deleteEntityById(id);
		TUser user=this.customUserService.getEntity(id);
		user.setUsable(0);
		this.customUserService.saveEntity(user);
		return "{\"success\":true}";
	}
//
//	@RequestMapping(value = { "/show" })
//	public String show(String id, Model model) {
//		if (StringUtils.isNotBlank(id)) {
//			TUser t = this.customUserService.getEntity(id);
//			model.addAttribute("entity", t);
//		}
//		return this.getMappingPath() + this.getEntityName() + "/show";
//	}
//
//	@RequestMapping(value = { "/edit" })
//	public String input(String id, Model model) {
//		if (StringUtils.isNotBlank(id)) {
//			TUser t = this.customUserService.getEntity(id);
//			model.addAttribute("entity", t);
//			// 鑾峰彇瀵瑰簲鐨勫啘鍦轰俊鎭�
//			List<TFarmUser> farmUserList = this.farmUserService.findList(Restrictions.eq("user", t));
//			model.addAttribute("farmUserList", farmUserList);
//		}
//		return this.getMappingPath() + this.getEntityName() + "/edit";
//	}

	@RequestMapping("/update")
	public String update(@ModelAttribute("preloadEntity") TUser entity) {
		this.customUserService.updateEntity(entity);
		return EntityController.REDIRECT_URL;
	}
//
//	@ModelAttribute("preloadEntity")
//	public TUser getEntity(@RequestParam(value = "id", required = false) String id) {
//		TUser entity = null;
//		if (StringUtils.isNotBlank(id)) {
//			entity = this.customUserService.getEntity(id);
//		} else {
//			entity = new TUser();
//		}
//		return entity;
//	}
//
//	@RequestMapping("/checkExist")
//	@ResponseBody
//	public Boolean checkUserName(String userName, String id) {
//		boolean result = false;
//		if (StringUtils.isBlank(id)) {
//			result = this.customUserService.checkNotExistByUserName(userName);
//		} else {
//			TUser user = this.customUserService.getUserByName(userName);
//			if (user != null && user.getId().equals(id)) {
//				result = true;
//			}
//		}
//		return result;
//	}
//
//	/**
//	 * 鎵归噺鍒犻櫎鐢ㄦ埛
//	 * 
//	 * @param ids
//	 * @return
//	 */
//	@RequestMapping(value = { "/deleteUsers" })
//	public String deleteUsers(String ids) {
//		logger.info("鎵归噺鍒犻櫎鐢ㄦ埛");
//		logger.info("ids = {}", ids);
//		if (StringUtils.isNotBlank(ids)) {
//			String[] strids = ids.split(",");
//			for (int i = 0; i < strids.length; i++) {
//				this.customUserService.deleteEntity(strids[i]);
//			}
//		}
//		return "redirect:index.action";
//	}
}